package com.hs.serial

import kotlin.experimental.xor

object Cmd {

    /**
     * 异或校验
     *
     * @param data 十六进制串
     * @return checkData  十六进制串
     */
   private fun xor_result(data: ByteArray): ByteArray {
        var checkData = 0
        for (i in data) {
            // 进行异或运算
            checkData = (i xor checkData.toByte()).toInt()
        }
        return data.plus(checkData.toByte())
    }


    fun openLamp(broadId: Int, channel: Int): ByteArray {
        val openLamp = byteArrayOf(0x57, 0x4B, 0x4C, 0x59, 0x09, 0x00, 0x88.toByte())
        openLamp[5] = (broadId and 0xFF).toByte()
        return xor_result(openLamp.plus(channel.toByte()))
    }

    fun closeLamp(broadId: Int, channel: ByteArray): ByteArray {
        val openLamp = byteArrayOf(0x57, 0x4B, 0x4C, 0x59, 0x09, 0x00, 0x95.toByte(), 0x00,channel.size.toByte())
        openLamp[5] = (broadId and 0xFF).toByte()
        val cmd = openLamp.plus(channel)
        cmd[4] =(cmd.size+1).toByte()
        return xor_result(cmd)
    }

    fun checkDoor(broadId: Int): ByteArray {
        val cmd = byteArrayOf(0x57, 0x4B, 0x4C, 0x59, 0x08, 0x00, 0x84.toByte())
        cmd[5] = (broadId and 0xFF).toByte()
        return xor_result(cmd)
    }
}
